package com.xinzhitong.www.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.xinzhitong.www.enumeration.GoodType;
import com.xinzhitong.www.exception.good.InvalidGoodException;
import com.xinzhitong.www.exception.good.OwnedGoodException;
import com.xinzhitong.www.pojo.Trade;
import com.xinzhitong.www.service.PayService;
import com.xinzhitong.www.utils.Message;
import com.xinzhitong.www.utils.PayUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 购买控制器
 *
 * @author 徐鑫
 */
@CrossOrigin
@RestController
@RequestMapping("pay")
public class PayController {

    @Resource
    PayService payService;

    /**
     * 获取购买某物品的支付宝URL参数
     *
     * @param goodId id
     * @return URL支付参数
     */
    @RequestMapping(value = "params", method = RequestMethod.GET)
    public Message params(
            @RequestParam("goodId") Integer goodId,
            @RequestParam("goodType") GoodType goodType
    ) {
        String msg;
        try {
            msg = payService.getParamsOfGoodOfId(goodId, goodType);
            return Message.createSuc(msg == null ? "获取成功，请前往我的购买查看" : msg);
        } catch (InvalidGoodException e) {
            e.printStackTrace();
            msg = "商品信息已失效";
        } catch (OwnedGoodException e) {
            e.printStackTrace();
            msg = "您已拥有该商品，无需重复购买";
        }
        return Message.createErr(msg);
    }

    /**
     * 支付
     *
     * @param request http请求
     * @return success或fail
     */
    @ResponseBody
    @RequestMapping("pay")
    public String pay(
            HttpServletRequest request
    ) {
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Object o : requestParams.keySet()) {
            String name = (String) o;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        String alipayPublicKey = PayUtil.getAlipayPublicKey();
        System.out.println(alipayPublicKey);
        try {
            //验签
            AlipaySignature.rsaCheckV2(params, alipayPublicKey, "UTF-8", "RSA2");
            //获取状态
            String tradeStatus = params.get("trade_status");
            System.out.println(tradeStatus);
            //处理货物内容
            Trade trade = PayUtil.getTradeFromOTN(params.get("out_trade_no"));//获取订单
            trade.setTotalAmount(Double.valueOf(params.get("total_amount")));//设置金额
            switch (tradeStatus) {
                case "WAIT_BUYER_PAY":
                    System.out.println("订单创建");
//                    payService.record(trade);
                    break;
                case "TRADE_SUCCESS":
                    System.out.println("订单创建");
                    System.out.println("订单发货");
                    payService.record(trade);
                    System.out.println("发货成功");
                    break;
            }
        } catch (AlipayApiException e) {
            System.out.println(new Date() + " fail");
            return "fail";
        }
        System.out.println(new Date() + " success");
        return "success";
    }

}
